package com.liujian.gymxmjpa.fontconntroller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.liujian.gymxmjpa.dao.*;
import com.liujian.gymxmjpa.dto.PrivateClassDto;
import com.liujian.gymxmjpa.entity.*;
import com.liujian.gymxmjpa.service.MChongzhiMyBaitisService;
import com.liujian.gymxmjpa.service.MLoosMyBaitisService;
import com.liujian.gymxmjpa.service.MenberMyBaitisService;
import com.liujian.gymxmjpa.service.PrivateCoachInfoMyBaitisService;
import com.liujian.gymxmjpa.utils.R;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

@CrossOrigin(origins = "*",allowCredentials = "true")
@RestController
@RequestMapping("/menber/font")
public class FontMenberConntroller {

    @Autowired
    private MenberDao menberDao;
    @Autowired
    private chongzhiDao chongzhiDao;
    @Resource
    RedisTemplate redisTemplate;
    @Resource
    MenberMyBaitisService menberMyBaitisService;
    @Resource
    MChongzhiMyBaitisService mChongzhiMyBaitisService;
    @Resource
    RestTemplate restTemplate;
    @Autowired
    private PrivateCoachInfoDao privateCoachInfoDao;
    @Autowired
    private CoachDao coachDao;
    @Autowired
    private SubjectDao subjectDao;
    @Autowired
    private PrivateCoachInfoMyBaitisService privateCoachInfoMyBaitisService;
    @Autowired
    private MLoosMyBaitisService mLoosMyBaitisService;

    //获取token
    @RequestMapping("/token")
    public R getToken(String memberPhone, String yzm){

        Member res = null;
        List<Member> list = menberDao.findAll();
        for (Member member : list) {
            if(member.getMemberPhone().equals(memberPhone)){
                res=member;
                break;
            }
        }
        if(res==null){
            return R.error();
        }

        //判断验证码是否正确
        Object co =  redisTemplate.opsForValue().get("18877429184");

        if(co==null){
            return R.error();
        }
        String code = (String) co;
        if(!code.equals(yzm)){
            return R.error();
        }

        String userJson = JSON.toJSONString(res);//序列化user
        JwtBuilder jwtBuilder = Jwts.builder(); //获得JWT构造器
        Map<String,Object> map=new Hashtable<>();
        map.put("kay",userJson);
        String token = jwtBuilder.setSubject("hello") //设置用户数据
                .setIssuedAt(new Date()) //设置jwt生成时间
                .setId("1") //设置id为token id
                .setClaims(map) //通过map传值
                .setExpiration(new Date(System.currentTimeMillis() + 50000000)) //设置token有效期
                .signWith(SignatureAlgorithm.HS256, "java666") //设置token加密方式和密码
                .compact(); //生成token字符串

        return R.ok().put("token",token).put("data",userJson);
    }

    //充值记录列表
    @RequestMapping("/congzhi/list")
    public R query1(Integer memberId ,Integer pageSize,Integer pageNumber,String sdate,String edate) throws ParseException {
        if(pageSize<0 || pageNumber<0 || memberId==0)return R.error();

        Pageable pageable= PageRequest.of(pageNumber-1,pageSize);
        //时间范围为空
        if(sdate==null || sdate.equals("") || edate==null || edate.equals("")){

            Page<MChongzhi> page = mChongzhiMyBaitisService.page(new Page<MChongzhi>(pageNumber, pageSize)
                    , new QueryWrapper<MChongzhi>().eq("Memberid", memberId));
            return R.ok().put("data",page);
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String startTime =sdf.format(sdf.parse(sdate));

        Calendar calendar = new GregorianCalendar();
        calendar.setTime(sdf.parse(edate));
        // 把日期往后增加一天,整数  往后推,负数往前移动
        calendar.add(Calendar.DATE, 1);
        // 这个时间就是日期往后推一天的结果
        String endTime =sdf.format(calendar.getTime());

        Page<MChongzhi> page = mChongzhiMyBaitisService.page(new Page<MChongzhi>(pageNumber, pageSize)
                , new QueryWrapper<MChongzhi>().eq("Memberid", memberId)
                        .between("Date",startTime,endTime));
        return R.ok().put("data",page);
    }

    //我的私教课列表
    @RequestMapping("/private/list")
    public R query2(Integer memberId ,Integer pageSize,Integer pageNumber) throws ParseException {
        if(memberId==0)return R.error();

        Page<MPrivateCoachInfo> page = privateCoachInfoMyBaitisService.page(new Page<MPrivateCoachInfo>(pageNumber,pageSize)
                , new QueryWrapper<MPrivateCoachInfo>().eq("memberid", memberId));
        List<PrivateClassDto> list=new ArrayList<>();
        List<MPrivateCoachInfo> records = page.getRecords();
        List<MMember> memberList = menberMyBaitisService.list();
        List<Coach> coachList = coachDao.findAll();
        List<Subject> subjectList = subjectDao.findAll();
        for (MPrivateCoachInfo record : records) {
            PrivateClassDto dto=new PrivateClassDto();
            dto.setDate(record.getDate());
            dto.setPrice(record.getRealprice());
            for (MMember member : memberList) {
                if(member.getMemberId()==record.getMemberid()){
                    dto.setUserName(member.getMemberName());
                    break;
                }
            }
            for (Coach coach : coachList) {
                if(coach.getCoachId()==record.getCoachid()){
                    dto.setCoachName(coach.getCoachName());
                    break;
                }
            }
            for (Subject subject : subjectList) {
                if(subject.getSubId()==record.getSubjectid()){
                    dto.setClassName(subject.getSubname());
                    break;
                }
            }
            list.add(dto);
        }
        Page<PrivateClassDto> res = new Page<>();
        res.setRecords(list);
        res.setSize(page.getSize());
        res.setCurrent(page.getCurrent());
        res.setTotal(page.getTotal());
        return R.ok().put("data",res);
    }

    //客服
    @RequestMapping("/ai")
    public R aiChat(String msg){
        Notice notice = restTemplate.getForObject("http://api.qingyunke.com/api.php?key=free&appid=0&msg="+msg
                , Notice.class);
        return R.ok().put("data",notice);
    }

    //物品遗失列表
    @RequestMapping("/loos/list")
    public R loosList(Integer pageSize,Integer pageNumber,String name) throws ParseException {
        Page<MLoos> page=null;
        if(name==null || name.isEmpty()){
            page = mLoosMyBaitisService.page(new Page<MLoos>(pageNumber, pageSize));
        }else{
            page = mLoosMyBaitisService.page(new Page<MLoos>(pageNumber, pageSize)
                ,new QueryWrapper<MLoos>().eq("loosName",name));
        }
        return R.ok().put("data",page);
    }



}
